package com.liqw.spi.listener;

import com.liqw.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.time.Duration;

// ======================== 启动监听器 ========================
@Slf4j
public class CustomRunListener implements SpringApplicationRunListener {
    public CustomRunListener(SpringApplication application, String[] args) {
        // 必须定义这个构造方法，以便 Spring 能正确初始化这个监听器
    }

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println(Constant.getStepStr("CustomRunListener.starting", Constant.MODE_SPI) + "CustomRunListener.starting  - 应用正在启动");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext ctx, ConfigurableEnvironment env) {
        System.out.println(Constant.getStepStr("CustomRunListener.environmentPrepared", Constant.MODE_SPI) + "CustomRunListener.environmentPrepared  - 环境已经准备好");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println(Constant.getStepStr("CustomRunListener.contextPrepared", Constant.MODE_SPI) + "CustomRunListener.contextPrepared  - 上下文已准备");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println(Constant.getStepStr("CustomRunListener.contextLoaded", Constant.MODE_SPI) + "CustomRunListener.contextLoaded  - 上下文已加载");
    }

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println(Constant.getStepStr("CustomRunListener.started", Constant.MODE_SPI) + "CustomRunListener.started  - 应用已启动！启动耗时：" + timeTaken.toMillis() + " 毫秒");
    }

    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println(Constant.getStepStr("CustomRunListener.ready", Constant.MODE_SPI) + "CustomRunListener.ready  - 应用已准备就绪！启动耗时：" + timeTaken.toMillis() + " 毫秒");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println(Constant.getStepStr("CustomRunListener.failed", Constant.MODE_SPI) + "CustomRunListener.failed  - 应用启动失败");
    }
}